﻿using System.IO;
using System;

namespace RightControl.Common{
    public class LogHelper {
        /// <summary>
        /// bidSerive专用
        /// </summary>
        /// <param name="str"></param>
        public static void WiteServiceLog(string str) {
            //string fileNm = "D:\\Program Files\\AutoBidSvr\\Log\\bidLog" + DateTime.Now.ToString("yyyyMMdd") + ".txt";

            //WiteToFile(str, fileNm);
        }

        public static void WriteErrLog(string str) {
            WriteLog(str, "ErrorLog");
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="str"></param>
        public static void WriteLog(string str, string logDir = "Log") {
            if (!Directory.Exists(logDir)) {
                Directory.CreateDirectory(logDir);
            }

            string fileNm = logDir + "\\log" + DateTime.Now.ToString("yyyyMMdd") + ".txt";

            WiteToFile(str, fileNm);
        }

        public static void WriteInfo(string str) {
            if (!Directory.Exists("Log")) {
                Directory.CreateDirectory("Log");
            }

            WiteToFile(str, "Info.txt");
        }
        //System.Web.HttpContext.Current.Server.MapPath

        public static void WriteWebLog(string str) {
            string logDir = Configs.GetValue("LogDir") + "/Log/";
            if (!Directory.Exists(logDir)) {
                Directory.CreateDirectory(logDir);
            }
            string fileNm = "log" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            string filePath = logDir + fileNm;

            WiteToFile(str, filePath);
        }

        public static void WriteWebLog(string str, Exception ex) {
            string logDir = Configs.GetValue("LogDir") + "/Log/";
            if (!Directory.Exists(logDir)) {
                Directory.CreateDirectory(logDir);
            }
            string fileNm = "log" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            string filePath = logDir + fileNm;
            string logstr = str + "\r\n" + ex.Message + "\r\n" + ex.StackTrace;
            WiteToFile(logstr, filePath);
        }

        private static void WiteToFile(string str, string filePath) {
            try {
                using (StreamWriter sw = new StreamWriter(filePath, true)) {
                    string spreatorLine = "--------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "-------------------------------";
                    sw.WriteLine(spreatorLine);
                    sw.WriteLine(str);
                    sw.WriteLine(spreatorLine);
                    sw.Close();
                }
            } catch (Exception) {
                
            }    
        }
    }
}
